#!/usr/bin/env python

import optparse
import shutil
import sys

import tables

from charmicat import BadCommandLineError

def main():
    '''
    ptmark_by_attr.py [opts] attr file.h5 [file.h5 [...]]

    Examine one or more PyTables input files and mark them by appending
    the value of the table attribute `attr' to the end of their filename.
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    op.add_option("-n", "--ntname", dest='nt', default='nt', 
                  help='Check table named NAME for length of zero',
                  metavar='NAME')

    opts, args = op.parse_args()

    if len(args) < 1:
        msg = "Please supply at least one PyTables file as input"
        raise BadCommandLineError(msg, -1)

    for i, path in enumerate(args):
        with tables.openFile(path) as fp:
            sys.stdout.write("{0}/{1} files complete\r".format(i, len(args)))
            sys.stdout.flush()

            nt = fp.getNode(fp.root, opts.nt)

            attr_value = getattr(nt.attrs, attr) 

            if len(nt) == 0:
                shutil.move(path, path + '.' + attr_value)

    print "{0}/{0} files complete\r".format(len(args))
    
    return 0



if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
